from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select, WebDriverWait
from selenium.common.exceptions import NoSuchElementException 
import unittest, time, re, datetime, os, random, traceback
import sys, argparse, optparse, pyodbc, inspect
import SeleniumTestHelper, SeleniumSQLHelper

file_name = os.path.relpath(__file__)[:-3]

class IWT_AVW(unittest.TestCase):
    """ ## NEED TO SET Variables to config.INTRAX config.Login)name etc.
    - unrefactored DB checks added  starting from bottom most testcase, to the top one: def x_test_pluto_avw_pax_address(self, rand_avw_addr=1):
    SeleniumTestHelper.SeleniumTestHelper.environment_setter(env_option)
    - random_avw_addr==1  then for row in range (but that's custom (like url)
    -@class method in Selenium helper doesn't allow me to use unittests in the helper
    - what about repeating variables like name of test and exception catching at end 
    - how to share variables between functions that can be dynamially updated as functions run
    -get element by sizzle returns unlclear message  when exception happens (index out of range)
    -mkae every tescase do a client side Exception catching by scanning source for erro
    -Need to make every testcase compare against DB  (COPY  from finished: pluto_pax_address)
    - Need to make every testcase check for #success message 
    - use AVW data input even for cases where no AVW?
    - update tests to always get fresh paxs via db query rather tham manually declared paxs
    - figure out if want to use internal error handling or append verification errors via try catch 
    
    """
    
   
    @classmethod
    def setUpClass(self):
        name_of_test=(str(inspect.stack()[0][3]))
        self.verificationErrors = []
        self.dirty_data=[]
        self.base_url = "http://"
        
        self.username = "ssaftest"
        self.lastName = "intraxSaf"
        self.dateTime=datetime.datetime.now().strftime("%Y%m%d%H%M")
        self.Season = "Spring 2013" # "Summer 2013"  "Winter 2013"
        self.country= "Thailand"   # Summer (may and june)>> Bulgaria # Winter (nov and dec)>>Brazil # Spring(mar and apr) >> Thailand 
        self.SeasonId = "16"  #Spring 2013.   select top 100* from ICDSeason
        #season start date will be X days before today
        self.season_start_date = datetime.datetime.now()- datetime.timedelta(days=21) #).strftime("%d.%m.%Y")
        self.season_end_date = datetime.datetime.now() + datetime.timedelta(days=30)  #).strftime("%d.%m.%Y")
        self.pax_start_date = self.season_start_date + datetime.timedelta(days=1)
        print
            

    def setUp(self):
        name_of_test=(str(inspect.stack()[0][3]))
        self.driver = webdriver.Firefox()
        #self.driver   = webdriver.Ie()
        self.driver.implicitly_wait(15)
        print
                        
                   
    def test_pluto_avw_pax_address(self, rand_avw_addr=1):
        try:
            """Full DB comparison test and most worked on one!! """
            name_of_test=(str(inspect.stack()[0][3]))
            self.driver.implicitly_wait(3)
            now = datetime.datetime.now()
            print (name_of_test," time is:  ", now.strftime("%Y-%m-%d %H:%M:%S"))
            driver = self.driver
            pluto_address_pax_id ="1031184" 
            checkIn_pax_email ="sk8723_can@yahoo.co.jpx"
    
    
#            # Login to Pluto
            SeleniumTestHelper.IWTtestHelper.intrax_login(driver,config.INTRAX, config.INTRAX_login)
    
            # Add Verified Address
            
            driver.get(self.base_url + config.INTRAX + "/icd/participant/viewICDParticipantAddresses.action?icdParticipantId=%s" % pluto_address_pax_id)
 
            tst_user_list = SeleniumTestHelper.SeleniumTestHelper.get_csv_data("iwt_users.csv")
            if rand_avw_addr==1:
                print "selecting a RANDOM address from address file"
                start_num=random.randrange(1,len(tst_user_list))
                #start_num=8  #3 or 8
                end_num=start_num+1
            else:
                print "Data driven testing through address list in desc order"
                start_num=1
                end_num=len(tst_user_list)
#            
#            For non-random tests
#            start_num=12
#            end_num=13


            for row in range(start_num,end_num):
                print ("Spreadsheet row #: ", row)
                csv_data= (tst_user_list[row][10],tst_user_list[row][11], tst_user_list[row][12]\
                , tst_user_list[row][13],tst_user_list[row][14],tst_user_list[row][15],tst_user_list[row][16],tst_user_list[row][17] )
            
                print "tst_user_list_row: ", csv_data
                print
                 
                driver.find_element_by_partial_link_text("Addresses").click()
                driver.find_element_by_css_selector("img[title=\"Add New U.S. Address\"]").click()
                    
                SeleniumTestHelper.IWTtestHelper.avw_test(driver,name_of_test,tst_user_list, row,0,"#submitButton")
                time.sleep(5)
                
                avw_success_element = '#successMessages'
                driver.find_element_by_css_selector(avw_success_element)
                
                
                address_result = SeleniumSQLHelper.sql_data_fetch("""
                select top 1 Street1, Street2, City, StateDtl.Abbr, PostalCode,
                  -- CAST(GeocodeId AS varchar(20)) as GeocodeID
                 convert(varchar(15), isnull(Longitude, 0)), convert(varchar(15), isnull(Latitude, 0)), convert(varchar(15), isnull(GeocodeID,0))
                 from address
                
                            """, pluto_address_pax_id)               
                time.sleep(3)               
                
            
                print "Address_result_from db: ", address_result[0][:], "address from CSV: ", csv_data
                self.assertEqual(tuple(address_result[0][:]),  (csv_data))                                       
                print
                        
                time.sleep(5)
                
        except Exception as e:
    
            exception_result = SeleniumTestHelper.SeleniumTestHelper.exception_found\
            (e,traceback.format_exc(), now, file_name, name_of_test, driver\
             ,['pluto_address_pax_id: %s' % pluto_address_pax_id, 'checkIn_pax_email: %s' % checkIn_pax_email])         
                                                                                      
            self.fail([exception_result])
            
            
    
                    
    def test_pluto_hc_deduper_hc_select(self, rand_avw_addr=1):
        try:
            name_of_test=(str(inspect.stack()[0][3]))
            self.driver.implicitly_wait(5)
            now = datetime.datetime.now()
            print (name_of_test," time is:  ", now.strftime("%Y-%m-%d %H:%M:%S"))
            driver = self.driver
            icdRipaId = '11000'

            SeleniumTestHelper.IWTtestHelper.intrax_login(driver,config.INTRAX, config.INTRAX_login)

            #Load Data and go to AVW page
            tst_user_list = SeleniumTestHelper.SeleniumTestHelper.get_csv_data("iwt_users.csv")
            #Example: using random number from list print random.randrange(1,len(pxr_job_change_pax_id))
            if rand_avw_addr==1:
                print "selecting a RANDOM address from address file"
                start_num=random.randrange(1,len(tst_user_list))
                end_num=start_num+1
            else:
                print "Data driven testing through address list in desc order"
                start_num=1
                end_num=len(tst_user_list)
                
            
            for row in range(start_num,end_num):
                print ("Spreadsheet row #: ", row)
                csv_data= (tst_user_list[row][10],tst_user_list[row][11], tst_user_list[row][12]\
                , tst_user_list[row][13],tst_user_list[row][14],tst_user_list[row][15],tst_user_list[row][16],tst_user_list[row][17] )
            
                print "tst_user_list_row: ", csv_data
                print
                driver.get(self.base_url + config.INTRAX + "/icd/ripa/company/editNewHostCompany.action?icdRipaId=%s" % icdRipaId)
                SeleniumTestHelper.IWTtestHelper.avw_test(driver,name_of_test,tst_user_list, row, 1,"input.continueJobChangeButton")
                time.sleep(5)
                
                avw_success_element = '#successMessages'
                driver.find_element_by_css_selector(avw_success_element)
                
                # removed party id from query as it uses sequential party id
                address_result = SeleniumSQLHelper.sql_data_fetch("""
                select top 1 Street1, Street2, City, StateDtl.Abbr, PostalCode,
                  -- CAST(GeocodeId AS varchar(20)) as GeocodeID
                 convert(varchar(15), isnull(Longitude, 0)), convert(varchar(15), isnull(Latitude, 0)), convert(varchar(15), isnull(GeocodeID,0))
                 from address

                
                            """)#, icdRipaId)              
                time.sleep(3)               
                
            
                print "Address_result_from db: ", address_result[0][:], "address from CSV: ", csv_data
                self.assertEqual(tuple(address_result[0][:]),  (csv_data))                                       
                print
                        
                time.sleep(5)
                
        except Exception as e:
    
            exception_result = SeleniumTestHelper.SeleniumTestHelper.exception_found\
            (e,traceback.format_exc(), now, file_name, name_of_test, driver\
             ,['icdRipaId: %s' % icdRipaId])         
                                                                                      
            self.fail([exception_result])
           
        
    def is_element_present(self, how, what):
        try: self.driver.find_element(by=how, value=what)
        except NoSuchElementException, e: return False
        return True
    
    
    def close_alert_and_get_its_text(self):
        try:
            alert = self.driver.switch_to_alert()
            if self.accept_next_alert:
                alert.accept()
            else:
                alert.dismiss()
            return alert.text
        finally: self.accept_next_alert = True 
    
    def tearDown(self):
        time.sleep(5)
        
        try:
            self.driver.quit()
        except Exception:
            print(" TearDown Method: Browser seems already closed.")
            pass
        
        
    @classmethod
    def tearDownClass(self):
        time.sleep(5)
        print(" ")
        print("Running: ",(inspect.stack()[0][3]))
        print ("This data needs investigation/cleanup: ",self.dirty_data)
        #self.assertEqual([], self.verificationErrors)
        print ("Failures: ",self.verificationErrors)
        
#        try:
#            self.driver.quit()
#            
#        except Exception:
#            print("Closing Webdriver in TearDown Class")
#            pass

if __name__ == '__main__':    
    #add you app's options here...
    option = SeleniumTestHelper.env_variable
    #locals().update(SeleniumTestHelper.SeleniumTestHelper.environment_setter(option))
    config = SeleniumTestHelper.SeleniumTestHelper.environment_setter(option)
        
    unittest.main()
    
    
    
